
import { assetsDB } from '@/indexDB/index'
import { HOLD_HISTORY_KEY } from '@/views/hold/model'
import { ref } from 'vue'

export interface HoldHistoryItem {
  // 取列表最新一个记录和当前记录作对比，大于一天就新增，否则仅更新
  id?: string | number // 历史id
  holdId: string | number // 持仓的id
  /**
   * @deprecated historyId已弃用，请使用 id 来代替。
   */
  historyId?: string | number // 旧id，已弃用
  createTime: string
  updateTime: string
  latestPrice: string | number
  holdNum: number
  holdPrice: number
  holdValue: number // 持仓市值
  holdEarnings: number // 持仓收益
  holdEarningsPercent: string // 持仓收益率,百分比
}

export const historyKeys = '++id, holdId, createTime, updateTime, latestPrice, holdNum, holdPrice, holdValue, holdEarnings, holdEarningsPercent'

export const historyList = ref<HoldHistoryItem[]>([])

export const initHistoryDB = async () => {
  const arr = await assetsDB.historyList.toArray()
  if (!arr.length) {
    const listStr = localStorage.getItem(HOLD_HISTORY_KEY)
    const list = listStr ? JSON.parse(listStr) : []
    const formattedList: HoldHistoryItem[] = list.map((history: HoldHistoryItem) => {
      // 以前的id是持仓id-holdId，以前的historyId是现在的id
      const { id, historyId } = history
      return {
        ...history,
        id: historyId,
        holdId: id
      }
    })

    await assetsDB.historyList.bulkAdd(formattedList)
    console.log('历史记录迁移成功!');
    updateHistoryList()
  } else {
    updateHistoryList()
  }
}

export const updateHistoryList = async () => {
  historyList.value = await assetsDB.historyList.where('holdNum').above(0).toArray()
  return Promise.resolve(historyList.value)
}